<template>
  <t-card class="card" :bordered="false" :style="{ width: `${toDoListConfig.cardWidth}px` }">
    <!-- 新增的右侧悬浮按钮 -->
    <t-button 
      class="collapse-btn"
      shape="circle"
      variant="outline"
      @click="handleToggleCollapse"
      :style="{ left : `${toDoListConfig.cardWidth+6}px`}"
    >
      <template #icon>
        <t-icon :name="!isCollapsed ? 'chevron-left' : 'chevron-right'" />
      </template>
    </t-button>
    <!-- 按钮盒子 -->
    <t-space class="btnBox" size="0">
      <t-popup trigger="click" placement="bottom-left">
        <t-button block variant="text" theme="primary">
          设置
          <template #icon>
            <t-icon name="setting" />
          </template>
        </t-button>
        <template #content>
          <div style="width: 200px; padding: 6px">
            <t-space direction="vertical" size="small" style="width: 100%">
              界面宽度：
              <t-slider v-model:value="toDoListConfig.cardWidth" :min="0" :max="500" />
              文字大小：
              <t-slider v-model:value="toDoListConfig.treeFontSize" :min="14" :max="18" />
              <t-button block size="small" theme="default" @click="handleResetConfig">恢复默认配置</t-button>
            </t-space>
          </div>
        </template>
      </t-popup>
      <t-button v-if="isExpand" block variant="text" theme="primary" @click="handleExpandOrCollapse(false)">
        折叠
        <template #icon>
          <t-icon name="fullscreen-exit" />
        </template>
      </t-button>
      <t-button v-else block variant="text" theme="primary" @click="handleExpandOrCollapse(true)">
        展开
        <template #icon>
          <t-icon name="fullscreen" />
        </template>
      </t-button>
      <t-button block variant="text" theme="primary" :loading="loading" @click="handleRefresh(false)">
        刷新
        <template #icon>
          <t-icon name="refresh" />
        </template>
      </t-button>
    </t-space>
    <!-- 待办树 -->
    <t-loading :loading="loading">
      <t-tree
        ref="treeRef"
        class="tree"
        :data="dataTree"
        activable
        :keys="{label:'label',value:'id',children:'children'}"
        expand-all
        hover
        :lazy="false"
        line
        
        :transition="false"
        height="calc(100vh - 249px)"
        @click="handleClickTreeNode"
      >
        <template #icon="{ node }">
          <t-icon v-if="['1', '2'].includes(node.data.msgType)" name="notification" style="color: red" />
          <t-icon v-else-if="['3'].includes(node.data.msgType) && node.data.oaType" name="task-checked" />
          <t-icon v-else-if="['3'].includes(node.data.msgType)" name="gesture-click" />
          <t-icon v-else-if="node.expanded" name="caret-down-small" />
          <t-icon v-else name="caret-right-small" />
        </template>
        <template #label="{ node }">
          <span :style="{ fontSize: `${toDoListConfig.treeFontSize}px` }">{{ node.label }}</span>
        </template>
      </t-tree>
    </t-loading>
  </t-card>
</template>

<script lang="ts" setup>
import { useLocalStorage } from '@vueuse/core';
import { MessagePlugin, TreeNodeModel } from 'tdesign-vue-next';
import { computed, nextTick, onMounted, onUnmounted, ref } from 'vue';
import { useRouter } from 'vue-router';

import { useDictionaryStore } from '@/store';
import disposableParams from '@/utils/disposableParams';
import { request } from '@/utils/request';

// 路由器
const router = useRouter();
// 字典仓库
const dictionaryStore = useDictionaryStore();
// 默认待办列表配置
const defaultToDoListConfig: { [key: string]: any } = {
  cardWidth: 360,
  treeFontSize: 14,
  // 添加默认的折叠状态
  collapsedNodes: [],
};
// 待办列表配置
const toDoListConfig = useLocalStorage<{ [key: string]: any }>('to-do-list-config', defaultToDoListConfig);
// 处理重置配置
const handleResetConfig = () => {
  Object.keys(defaultToDoListConfig).forEach((key) => {
    toDoListConfig.value[key] = defaultToDoListConfig[key];
  });
};
const scrollTop = ref(0);
// 是否展开
const isExpand = ref(true);
// 加载状态
const loading = ref(false);
// 数据树
const dataTree = ref<Record<string, any>[]>([]);
// 保存当前折叠状态
const saveCollapsedState = () => {
  if (!treeRef.value) return;
  const collapsedNodes: string[] = [];
  const nodeList = treeRef.value.getItems();
  nodeList.forEach((node: TreeNodeModel) => {
    if (!node.expanded) {
      collapsedNodes.push(node.value);
    }
  });
  toDoListConfig.value.collapsedNodes = collapsedNodes;
};

// 恢复折叠状态
const restoreCollapsedState = () => {
  if (!treeRef.value || !toDoListConfig.value.collapsedNodes) return;
  const collapsedNodes = toDoListConfig.value.collapsedNodes;
  if (!Array.isArray(collapsedNodes)) return;
  
  const nodeList = treeRef.value.getItems();
  nodeList.forEach((node: TreeNodeModel) => {
    if (collapsedNodes.includes(node.value)) {
      treeRef.value.setItem(node.value, { expanded: false });
    }
  });
};
// 处理删除空子节点
const handleDeleteEmptyChildren = (arr: Record<string, any>[]) => {
  const deleteIndexs: number[] = [];
  arr.forEach((item, index) => {
    if (item.children && Array.isArray(item.children) && item.children.length) {
      handleDeleteEmptyChildren(item.children);
    }
    if (!item.children?.length && !item.orderIds && !item.clueIds) {
      deleteIndexs.unshift(index);
    }
  });
  deleteIndexs.forEach((index) => arr.splice(index, 1));
  return arr;
};
// 处理获取数据树
const handleGetDataTree = () => {
  loading.value = true;
  request
    .get({ url: '/system/message-notify/get-message-tree' })
    .then((data) => {
      dataTree.value = handleDeleteEmptyChildren(data);
    })
    .finally(() => {
      loading.value = false;
    });
};
// 组件挂载时
onMounted(() => {
  handleGetDataTree(); // 初始加载
  startAutoRefresh();  // 启动定时刷新
});
// 组件卸载时
onUnmounted(() => {
  // 清除定时器
  if (refreshTimer.value) {
    clearInterval(refreshTimer.value);
  }
});
// 处理点击树节点
const handleClickTreeNode = ({ node: { data } }: { node: TreeNodeModel<any> }) => {
  if(data.children) return
  
  let path = '';
  if (data.msgType === '1') {
    path = '/notice/list';
  } else {
    let operateTypeConfig = { path: '' };
    try {
      const operateTypeDictionary: Record<string, any> =
        dictionaryStore.get('decoration_order_operate_type').find((item) => item.value === data.operateType) || {};
      operateTypeConfig = JSON.parse(operateTypeDictionary.remark);
      console.log(operateTypeDictionary,'operateTypeDictionary');
    } catch {
      MessagePlugin.warning('解析操作配置失败，请联系管理员。');
      return;
    }
    path = operateTypeConfig.path;
  }
  if (!path) {
    MessagePlugin.warning('未匹配到相对应页面，请联系管理员。');
    return;
  }
  disposableParams.set('to-do-tree-jump-params', {
    noticeIds: data.ids,
    orderIds: data.orderIds,
    operateType: data.operateType,
    oaType: data.oaType,
    clueIds: data.clueIds,
    stageType: data.stageType,
  });
  router.push({ path, query: { timeStamp: new Date().getTime() } });
};
// 处理刷新
const handleRefresh = (silent = false) => {
  saveCollapsedState(); // 刷新前保存当前折叠状态
    loading.value = true;
  request
    .get({ url: '/system/message-notify/get-message-tree' })
    .then((data) => {
      const newData = handleDeleteEmptyChildren(data);
      
      if (!silent) {
        dataTree.value = newData;
        nextTick(() => {
          restoreCollapsedState(); // 恢复折叠状态
          // treeRef.value?.scrollTo({ index: 0 }); // 滚动到第一个节点   
          MessagePlugin.success('刷新成功');
        });
      } else {
        dataTree.value = newData;
        nextTick(() => {
          restoreCollapsedState(); // 恢复折叠状态
        });
      }
    })
    .finally(() => {
      loading.value = false;   
    });
};
// 树ref
const treeRef = ref();
// 处理展开或者折叠
const handleExpandOrCollapse = (expanded: boolean) => {
  const nodeList = treeRef.value.getItems();
  nodeList.forEach((node: TreeNodeModel) => {
    treeRef.value.setItem(node.value, { expanded });
  });
  isExpand.value = expanded;
};
// 定时器引用
const refreshTimer = ref<NodeJS.Timeout | null>(null);
// 启动定时刷新
const startAutoRefresh = () => {
  // 先清除已有定时器
  if (refreshTimer.value) {
    clearInterval(refreshTimer.value);
  }
  // 设置新的定时器（每分钟刷新一次）
  refreshTimer.value = setInterval(() => {
    handleRefresh(true);
  }, 60 * 1000); // 60秒 = 60000毫秒
};
// 脚本部分修改
const isCollapsed = ref(false);

const handleToggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value;
  if(isCollapsed.value) {
    toDoListConfig.value.cardWidth = 0
  } else {
    toDoListConfig.value.cardWidth = 360
  }
};
defineExpose({
  widht: computed(() => toDoListConfig.value.cardWidth),
});
</script>

<style lang="less" scoped>
.card {
  margin-right: 10px;
  position: sticky;
  top: 80px;

  :deep(.t-card__body) {
    padding: 4px;
  }

  .tree {
    &::-webkit-scrollbar {
      width: 8px;
      background: transparent;
    }

    &::-webkit-scrollbar-thumb {
      border-radius: 6px;
      border: 2px solid transparent;
      background-clip: content-box;
      background-color: var(--td-scrollbar-color);
    }
  }

  .btnBox {
    width: 100%;
    border-bottom: 1px solid var(--td-border-level-1-color);
    padding-bottom: 4px;
  }
  .collapse-btn {
    position: fixed;
    top:50vh;
    z-index:999;
    width: 24px;
    height: 24px;
  }
}
</style>

